package com.star.controller.admin;

import com.star.dto.SetmealPageQueryDTO;
import com.star.entity.Setmeal;
import com.star.result.PageResult;
import com.star.result.Result;
import com.star.service.SetmealService;
import com.star.vo.SetmealVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController("adminSetmealController")
@RequestMapping("/admin/setmeal")
@Slf4j
// Swagger接口文档
@Api(tags = "管理员端套餐管理接口")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private RedisTemplate<String, List<Setmeal>> redisTemplate;

    /**
     * 套餐分页查询
     * @param setmealPageQueryDTO
     * @return
     */
    @GetMapping("/page")
    @ApiOperation("套餐分页查询")
    public Result<PageResult> page(SetmealPageQueryDTO setmealPageQueryDTO){
        log.info("套餐分页查询{}",setmealPageQueryDTO);
        PageResult pageResult = setmealService.pageQuery(setmealPageQueryDTO);
        return Result.success(pageResult);
    }

    /**
     * 根据id查询套餐
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation("根据id查询套餐")
    public Result<SetmealVO> getById(@PathVariable Long id){
        log.info("根据id查询套餐{}",id);
        SetmealVO setmealVO = setmealService.getById(id);
        return Result.success(setmealVO);
    }

    /**
     * 套餐起售、停售
     * @param status
     * @param id
     * @return
     */
    @PostMapping("/status/{status}")
//    @CacheEvict(value = "setmealCache", allEntries = true)
    public Result<String> updateStatus(@PathVariable Integer status, Long id){
        log.info("套餐起售、停售{}{}",status,id);
        setmealService.updateStatus(status, id);

        clearSetmeal("setmeal_*");
        return Result.success();
    }
    /**
     * 清除redis缓存数据
     * @param pattern
     */
    private void clearSetmeal(String pattern){
        Set<String> keys = redisTemplate.keys(pattern);
        if(keys != null){
            redisTemplate.delete(keys);
        }
    }
}
